<template>
  <div class="uart-nrz-config-container">
    <!-- <el-card> -->
    <div slot="header">
      <!-- Config Form -->
      <el-row :gutter="2" class="config-form-row">
        <el-col :span="6">
          <span class="config-header">串口配置</span>
        </el-col>
        <el-col :span="6">
          <span class="show-info">工作模式:{{ workMode }}</span>
          <!-- </el-form-item> -->
        </el-col>
        <el-col :span="6">
          <!-- <el-form-item label="双工方式:"> -->
          <span class="show-info">双工方式:{{ doubleMode }}</span>
          <!-- </el-form-item> -->
        </el-col>
        <!-- <el-col :span="6">
          <el-button type="primary" icon="el-icon-plus" size="mini" class="header-button" @click="adduartConfigRow"></el-button>
        </el-col> -->
      </el-row>
    </div>

    <!-- Config Table -->
    <el-form ref="uartForm" :model="uartConfig" :rules="uartFormRules" size="mini" label-width="150px">
      <el-row :gutter="10">
        <el-col :span="24">
          <el-table :data="uartConfig.uart" :height="tableHeight" border size="mini" fit>
            <el-table-column label="串口" width="100px" align="center">
              <template slot-scope="scope">
                <span>S{{ scope.row.uartId }}</span>
              </template>
            </el-table-column>
            <el-table-column label="波特率(bps)">
              <template slot-scope="scope">
                <el-form-item :prop="'uart.' + scope.$index + '.baud'" :rules="uartFormRules.baud" label-width="0">
                  <el-input v-model.number="scope.row.baud"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="clockMode" label="时钟模式">
              <template slot-scope="scope">
                <el-form-item :prop="'uart.' + scope.$index + '.clockMode'" label-width="0">
                  <el-select v-model.number="scope.row.clockMode" placeholder="选择时钟模式">
                    <el-option label="常规" :value="0"></el-option>
                    <el-option label="从时钟(外时钟)" :value="1"></el-option>
                    <el-option label="主时钟" :value="2"></el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="sendClock" label="发送触发">
              <template slot-scope="scope">
                <el-form-item :prop="'uart.' + scope.$index + '.sendClock'" label-width="0">
                  <el-select v-model.number="scope.row.sendClock" placeholder="选择发送触发">
                    <el-option label="时钟上升沿" :value="0"></el-option>
                    <el-option label="时钟下降沿" :value="1"></el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="recvClock" label="接收触发">
              <template slot-scope="scope">
                <el-form-item :prop="'uart.' + scope.$index + '.recvClock'" label-width="0">
                  <el-select v-model.number="scope.row.recvClock" placeholder="选择接收触发">
                    <el-option label="时钟上升沿" :value="0"></el-option>
                    <el-option label="时钟下降沿" :value="1"></el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="protocol" label="协议标准">
              <template slot-scope="scope">
                <el-form-item :prop="'uart.' + scope.$index + '.protocol'" label-width="0">
                  <el-select v-model.number="scope.row.protocol" placeholder="选择协议标准">
                    <el-option label="CRC-16/CCITT" :value="0"></el-option>
                    <!-- <el-option label="其他" :value="1"></el-option> -->
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="" label="别名" align="center">
              <template slot-scope="scope">
                <el-form-item :prop="'uart.' + scope.$index + '.alias'" :rules="uartFormRules.alias" label-width="0">
                  <el-input v-model="scope.row.alias" clearable @clear="clearAlias(scope.$index)"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="enableCrc" label="CRC使能" width="100px" align="center">
              <template slot-scope="scope">
                <el-form-item :prop="'uart.' + scope.$index + '.enableCrc'" label-width="0">
                  <el-checkbox v-model.number="scope.row.enableCrc" :true-label="1" :false-label="0"></el-checkbox>
                </el-form-item>
              </template>
            </el-table-column>
            <!-- <el-table-column label="操作" width="140px" align="center">
              <template slot-scope="scope">
                <el-button type="danger" size="mini" @click="removeUartConfigRow(scope.$index)">删除</el-button>
              </template>
            </el-table-column> -->
          </el-table>
        </el-col>
      </el-row>
    </el-form>
  <!-- </el-card> -->
  </div>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
  data() {
    // 校验规则函数
    var validateBaud = (rule, value, callback) => {
      if (value === undefined || value === null || value.toString().trim() === '') {
        callback(new Error('波特率不能为空'))
      } else if (!/^\d+$/.test(value)) {
        callback(new Error('波特率必须为数字'))
      } else if (parseInt(value) <= 0 || parseInt(value) > 115200) {
        callback(new Error('波特率必须在1到115200之间'))
      } else {
        callback()
      }
    }

    var getByteLength = function(str) {
      var len = 0
      for (var i = 0; i < str.length; i++) {
        if (str.charCodeAt(i) > 127 || str.charCodeAt(i) === 94) {
          len += 2
        } else {
          len++
        }
      }
      return len
    }

    // 要限制最大数据长度为40字节
    var validateAlias = (rule, value, callback) => {
      if (value === undefined || value === null || value.toString().trim() === '') {
        callback(new Error('别名不能为空'))
      } else if (getByteLength(value) > 40) {
        callback(new Error('别名长度不能超过40字节'))
      } else {
        callback()
      }
    }

    return {
      doubleMode: '全双工',
      workMode: '单工',
      tableHeight: 'calc(100vh - 270px)',
      // uartConfig: {
      //   uart: []
      // },
      uartFormRules: {
        baud: [
          { required: true, message: '请输入波特率', trigger: 'blur' },
          { validator: validateBaud, trigger: 'blur' }
        ],
        alias: [
          { required: true, message: '请输入别名', trigger: 'blur' },
          { validator: validateAlias, trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters(['SysCfgInfo']),
    uartConfig() {
      return this.SysCfgInfo
    }
  },
  created() {
    // this.getSysCfg()
  },
  beforeDestroy() {
  },
  methods: {
    adduartConfigRow() {
      this.uartConfig.uart.push({
        uartId: 'S0',
        alias: 'uart0',
        baud: 64000,
        clockMode: 1,
        sendClock: 1,
        recvClock: 1,
        protocol: 1,
        enableCrc: 1
      })
      this.$nextTick(() => this.$refs.uartForm.clearValidate())
    },
    removeUartConfigRow(index) {
      this.uartConfig.uart.splice(index, 1)
      this.$nextTick(() => this.$refs.uartForm.clearValidate())
    },
    save() {
      return new Promise((resolve, reject) => {
      // Implement the logic to save the uart-NRZ configuration
        this.$refs.uartForm.validate((valid) => {
          if (valid) {
            resolve(true)
          } else {
            this.$message.warning('串口配置标签表单校验失败')
            resolve(false)
          }
        })
      })
    },
    getSettings() {
      console.log('getSettings')
      this.$nextTick(() => this.$refs.uartForm.clearValidate())
    },
    getSysCfg(flag = 0) {
      this.loading = true
      this.$store.dispatch('device/getSysCfg').then(res => {
        this.loading = false
        this.uartConfig.uart = res.uart
        this.$nextTick(() => this.$refs.uartForm.clearValidate())
        if (flag === 1) {
          this.$message.success('串口配置获取成功')
        }
      }).catch(() => {
        this.loading = false
      })
    },
    clearAlias(index) {
      this.$refs.uartForm.validateField('uart.' + index + '.alias')
    }
  }
}
</script>

<style scoped>
.uart-nrz-config-container {
  padding: 10px;
}

.config-form-row {
  margin-bottom: 10px;
}

.config-header {
  font-size: 16px;
  font-weight: bold;
}

.show-info{
  font-size: 14px;
  color: #606266;
}

.header-button {
    float: right;
}
</style>
